﻿using System;
using System.Collections.Generic;

public class BindableList<T>
{
    public int Count { get { return list.Count; } }

    List<T> list = new List<T>();

    Action<List<T>> OnValueChange;

    public T this[int index]
    {
        get { return list[index]; }
    }

    public void Clear()
    {
        list.Clear();
    }

    public bool Contains(T item)
    {
        return list.Contains(item);
    }

    public void Add(T item, bool publish = false)
    {
        list.Add(item);
        if (publish) { Publish(); }
    }

    public void Remove(T item, bool publish = false)
    {
        list.Remove(item);
        if (publish) { Publish(); }
    }

    public void AddRange(IEnumerable<T> collection, bool publish = true)
    {
        list.AddRange(collection);
        if (publish) { Publish(); }
    }

    public void ForEach(Action<T> action)
    {
        list.ForEach(action);
    }

    public void Sort(Comparison<T> comparison)
    {
        list.Sort(comparison);
    }

    public bool IsSubscribe(Action<List<T>> valueChange)
    {
        Delegate[] delegates = OnValueChange.GetInvocationList();
        return Array.IndexOf(delegates, valueChange) > 0;
    }

    public void Subscribe(Action<List<T>> valueChange)
    {
        OnValueChange += valueChange;
    }

    public void Unsubscribe(Action<List<T>> valueChange)
    {
        OnValueChange -= valueChange;
    }

    public void Publish()
    {
        if (OnValueChange != null)
        {
            OnValueChange(list);
        }
    }

    public void Freed()
    {
        OnValueChange = null;
    }
}